const LoginService = require('../services/login-services')
const JSONResult =  require("../bean/json-result")
const service = new LoginService()

class LoginController{

    constructor(service = new LoginService()) {
        this.service = service
    }

    async toLoginPage(req,res,next){
        res.render("login",{title:"登录页面"})
        next()
    }

    async login(req,res,next){
        const {path,params,query,body:{username,password}} = req
        const RowDataPacket = await service.getUser(username,password)
        console.log("RowDataPacket[0]:",RowDataPacket[0])
        const {id,nickname,avatar,email,role,age,sex,wechat,QQ,phone,address} = RowDataPacket[0]
        let json = {}
        if (id) {
            const user = {
                userId:id,
                username:username,
                password:password,
                nickname:nickname,
                avatar:avatar,
                email:email,
                role:role,
                age:age,
                sex:sex,
                phone:phone,
                wechat:wechat,
                QQ:QQ,
                address:address
            }
            //设置session
            req.session.user = user
            json = new JSONResult({code:200,message:"登陆成功！",data:{user:user}})
        } else {
            json = new JSONResult({code:404,message:"登陆失败，用户名密码错误！",data:{user:null}})
        }
        res.json(json)
        next()
    }

    async logout(req,res,next){
        req.session.destroy(function() {
            res.redirect('/login.html');
        });
        next()
    }
}

module.exports = new LoginController()
